<template>
  <div class="profile-container">
    <div class="page-header">
      <h2>个人中心</h2>
    </div>
    
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>个人信息</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="editProfile = true">编辑</el-button>
          </div>
          <div class="profile-info">
            <div class="avatar-container">
              <img :src="userInfo.avatar || 'https://via.placeholder.com/150'" class="avatar-image">
            </div>
            <div class="info-item">
              <span class="label">用户名:</span>
              <span class="value">{{ userInfo.username }}</span>
            </div>
            <div class="info-item">
              <span class="label">昵称:</span>
              <span class="value">{{ userInfo.nickname }}</span>
            </div>
            <div class="info-item">
              <span class="label">邮箱:</span>
              <span class="value">{{ userInfo.email }}</span>
            </div>
            <div class="info-item">
              <span class="label">手机:</span>
              <span class="value">{{ userInfo.phone }}</span>
            </div>
            <div class="info-item">
              <span class="label">角色:</span>
              <span class="value">{{ roleText }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="16">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>修改密码</span>
          </div>
          <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="100px">
            <el-form-item label="原密码" prop="oldPassword">
              <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码"></el-input>
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码"></el-input>
            </el-form-item>
            
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码"></el-input>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="changePassword" :loading="loading">修改密码</el-button>
              <el-button @click="resetPasswordForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 编辑个人信息对话框 -->
    <el-dialog title="编辑个人信息" :visible.sync="editProfile" width="500px">
      <el-form ref="profileForm" :model="profileForm" :rules="profileRules" label-width="100px">
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="uploadAvatar"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload">
            <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="profileForm.nickname"></el-input>
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email"></el-input>
        </el-form-item>
        
        <el-form-item label="手机" prop="phone">
          <el-input v-model="profileForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editProfile = false">取消</el-button>
        <el-button type="primary" @click="updateProfile" :loading="loading">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { uploadFile } from '@/api/file';

export default {
  name: 'Profile',
  data() {
    // 确认密码验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };
    
    return {
      loading: false,
      editProfile: false,
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      profileForm: {
        nickname: '',
        email: '',
        phone: '',
        avatar: ''
      },
      profileRules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['userInfo']),
    roleText() {
      const roleMap = {
        0: '学生',
        1: '教师',
        2: '管理员'
      };
      return roleMap[this.userInfo.role] || '未知';
    }
  },
  created() {
    this.initProfileForm();
  },
  methods: {
    initProfileForm() {
      this.profileForm = {
        nickname: this.userInfo.nickname,
        email: this.userInfo.email,
        phone: this.userInfo.phone,
        avatar: this.userInfo.avatar
      };
    },
    uploadAvatar(options) {
      const { file } = options;
      this.loading = true;
      uploadFile(file)
        .then(response => {
          this.profileForm.avatar = response.data.url;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          this.$message.error('上传头像失败');
        });
    },
    handleAvatarSuccess(res, file) {
      // 实际项目中应该使用后端返回的URL
      this.profileForm.avatar = res.url || URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    updateProfile() {
      this.$refs.profileForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          // 模拟API调用
          setTimeout(() => {
            this.$message({
              type: 'success',
              message: '个人信息更新成功!'
            });
            this.editProfile = false;
            this.loading = false;
          }, 1000);
        } else {
          return false;
        }
      });
    },
    changePassword() {
      this.$refs.passwordForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          // 模拟API调用
          setTimeout(() => {
            this.$message({
              type: 'success',
              message: '密码修改成功!'
            });
            this.resetPasswordForm();
            this.loading = false;
          }, 1000);
        } else {
          return false;
        }
      });
    },
    resetPasswordForm() {
      this.$refs.passwordForm.resetFields();
    }
  }
};
</script>

<style lang="scss" scoped>
.profile-container {
  .page-header {
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 22px;
      font-weight: bold;
    }
  }
  
  .profile-info {
    .avatar-container {
      text-align: center;
      margin-bottom: 20px;
      
      .avatar-image {
        width: 100px;
        height: 100px;
        border-radius: 50%;
      }
    }
    
    .info-item {
      margin-bottom: 15px;
      
      .label {
        font-weight: bold;
        margin-right: 10px;
        color: #606266;
      }
      
      .value {
        color: #303133;
      }
    }
  }
  
  .avatar-uploader {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      
      &:hover {
        border-color: #409EFF;
      }
    }
    
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }
    
    .avatar {
      width: 100px;
      height: 100px;
      display: block;
      border-radius: 50%;
    }
  }
}
</style> 